/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.modules.admin.dto.BuildingUserContractDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.ElevatorMaintainStatusEnums;
import org.springblade.modules.admin.mapper.BuildingUserMapper;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.BuildingUserContractVO;
import org.springblade.modules.admin.mapper.BuildingUserContractMapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.admin.vo.BuildingUserVO;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户使用单位-合同统计信息 服务实现类
 *
 * @author ysq
 * @since 2025-08-19
 */
@Service
public class BuildingUserContractServiceImpl extends BaseServiceImpl<BuildingUserContractMapper, BuildingUserContract> implements IBuildingUserContractService {

	@Autowired
	private IBuildingFloorElevatorService buildingFloorElevatorService;

	@Autowired
	private IDictService dictService;

	@Autowired
	@Lazy
	private IElevatorDetailService elevatorDetailService;

	@Autowired
	private BuildingUserMapper buildingUserMapper;

	@Autowired
	@Lazy
	private BuildingService buildingService;

	@Override
	public void buildingUserContractJob() {
		//合同统计map
		Map<Long, List<BuildingUserContract>> listMap = this.list().stream().collect(Collectors.groupingBy(BuildingUserContract::getBuildingId));
		List<Building> buildingList = buildingService.list();

		//电梯查询信息
		List<BuildingUserContractVO> list = baseMapper.getElevatorContractInfo();
		Map<Long, List<BuildingUserContractVO>> longListMap = list.stream().collect(Collectors.groupingBy(BuildingUserContractVO::getBuildingId));

		//位置信息
		Map<Long, List<ElevatorDetail>> eleMap = elevatorDetailService.listAll().stream().collect(Collectors.groupingBy(ElevatorDetail::getBuildingId));

		//楼栋
		Map<Long, List<BuildingFloorElevator>> floorMap = buildingFloorElevatorService.list().stream().collect(Collectors.groupingBy(BuildingFloorElevator::getBuildingId));

		//项目id
		List<Long> buildingIds = list.stream().map(BuildingUserContractVO::getBuildingId).distinct().collect(Collectors.toList());

		//字典map
		Map<String, List<Dict>> buildingTypeMap = dictService.list(Wrappers.<Dict>lambdaQuery().eq(Dict::getCode, "building_type")).stream().collect(Collectors.groupingBy(Dict::getDictKey));

		List<BuildingUserContract> updateList = new ArrayList<>(16);
		for (Building building : buildingList) {
			Long buildingId = building.getId();
			if(buildingId.equals(1965590790046220290L)){
				System.out.println(123);
			}
			BuildingUserContract buildingUserContract;
			List<BuildingUserContract> userContracts = listMap.get(buildingId);
			if (userContracts != null) {
				buildingUserContract = userContracts.get(0);
			} else {
				buildingUserContract = new BuildingUserContract();
			}
			buildingUserContract.setTenantId(building.getTenantId());
			buildingUserContract.setBuildingId(buildingId);
			List<String> status = new ArrayList<>(5);
			if (buildingIds.contains(buildingId)) {
				List<BuildingUserContractVO> contractVOList = longListMap.get(buildingId);
				//潜在
				List<BuildingUserContractVO> disList = contractVOList.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.NO_STATUS.getId()).collect(Collectors.toList());
				if (disList.size() == contractVOList.size()) {
					buildingUserContract.setJoinHandsType(3);
					status.add("3");
				} else {
					if (disList.size() > 0) {
						status.add("3");
					}
				}
				//丢保
				List<BuildingUserContractVO> releaseInsuranceList = contractVOList.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.RELEASE_INSURANCE.getId()).collect(Collectors.toList());
				buildingUserContract.setDbEleCounts(releaseInsuranceList.size());
				//所有丢保才是丢保
				if (releaseInsuranceList.size() == contractVOList.size()) {
					buildingUserContract.setJoinHandsType(2);
					status.add("2");
				} else {
					if (releaseInsuranceList.size() > 0) {
						status.add("2");
					}
				}
				//脱保--也是合作中
				List<BuildingUserContractVO> inTimeList = contractVOList.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.DIS_ENABLE.getId()).collect(Collectors.toList());
				List<BuildingUserContractVO> stopList = contractVOList.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId()).collect(Collectors.toList());
				buildingUserContract.setOutTimeEleCounts(stopList.size());
				buildingUserContract.setInTimeEleCounts(inTimeList.size() + stopList.size());
				if (inTimeList.size() > 0 || stopList.size() > 0) {
					buildingUserContract.setJoinHandsType(1);
					status.add("1");
				}
			} else {
				buildingUserContract.setJoinHandsType(3);
				status.add("3");
			}
			buildingUserContract.setJoinHandsTypes(String.join(",", status));
			//处理项目类型
			if (building.getType() != null && buildingTypeMap.get(building.getType()) != null && buildingTypeMap.get(building.getType()).size() > 0) {
				String dictValue = buildingTypeMap.get(building.getType()).get(0).getDictValue();
				buildingUserContract.setBuildingTypeName(dictValue);
			}

			//处理楼栋
			List<BuildingFloorElevator> buildingFloorElevators = floorMap.get(buildingId);
			if (buildingFloorElevators != null && buildingFloorElevators.size() > 0) {
				buildingUserContract.setFloorType(1);
				buildingUserContract.setFloorCounts(buildingFloorElevators.size());
			} else {
				buildingUserContract.setFloorType(0);
				buildingUserContract.setFloorCounts(0);
			}

			//处理电梯位置
			List<ElevatorDetail> elevatorDetails = eleMap.get(buildingId);
			buildingUserContract.setElevatorGpsType(0);
			buildingUserContract.setElevatorCounts(0);
			if (elevatorDetails != null && elevatorDetails.size() > 0) {
				List<ElevatorDetail> detailList = elevatorDetails.stream().filter(o -> StrUtil.isEmpty(o.getLocationAddress())).collect(Collectors.toList());
				if (detailList.size() == 0) {
					buildingUserContract.setElevatorGpsType(1);
				}
				buildingUserContract.setElevatorCounts(elevatorDetails.size());
				List<ElevatorDetail> details = elevatorDetails.stream().filter(o -> Convert.toInt(o.getIsQuestion(), 0) == 1).collect(Collectors.toList());
				buildingUserContract.setQuestionEleCounts(details.size());
			} else {
				buildingUserContract.setElevatorCounts(0);
				buildingUserContract.setQuestionEleCounts(0);
			}
			//处理电梯问题
			updateList.add(buildingUserContract);
		}

		List<List<BuildingUserContract>> listList = Lists.partition(updateList, 20);
		for (List<BuildingUserContract> list1 : listList) {
			this.saveOrUpdateBatch(list1);
		}
	}

	@Override
	public IPage<BuildingUserContract> page(BuildingUserContractDTO buildingUserContractDTO) {
		Query query = new Query();
		query.setSize(buildingUserContractDTO.getSize());
		query.setCurrent(buildingUserContractDTO.getCurrent());
		IPage<BuildingUserContract> page = Condition.getPage(query);
		List<BuildingUserContract> list = baseMapper.page(buildingUserContractDTO.getSize() != 0 ? page : null, buildingUserContractDTO);

		List<MaintainPlanConfig> planConfigList = buildingUserMapper.getBuildingUserStatus(buildingUserContractDTO.getBuildingUserId(), null);
		Map<Long, List<MaintainPlanConfig>> listMap = planConfigList.stream().filter(o -> o.getBuildingId() != null).collect(Collectors.groupingBy(MaintainPlanConfig::getBuildingId));
		for (BuildingUserContract buildingUserContract : list) {
			List<MaintainPlanConfig> maintainPlanConfigs = listMap.get(buildingUserContract.getBuildingId());
			if (maintainPlanConfigs == null || maintainPlanConfigs.size() == 0) {
				continue;
			}
			//计算服务梯数
			buildingUserContract.setInTimeEleCounts(maintainPlanConfigs.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.CONTRACT_IN_TIME.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.CONTRACT_OUT_TIME.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.DIS_ENABLE.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId()).collect(Collectors.toList()).size());
			//计算脱保电梯
			buildingUserContract.setOutTimeEleCounts(maintainPlanConfigs.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END.getId() || o.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId()).collect(Collectors.toList()).size());
			//计算丢保
			buildingUserContract.setDbEleCounts(maintainPlanConfigs.stream().filter(o -> o.getMaintainStatus() == ElevatorMaintainStatusEnums.RELEASE_INSURANCE.getId()).collect(Collectors.toList()).size());

			//计算问题电梯数
			buildingUserContract.setQuestionEleCounts(maintainPlanConfigs.stream().filter(o -> Convert.toInt(o.getIsQuestion(), 0) == 1).collect(Collectors.toList()).size());

		}
		page.setRecords(list);
		return page;
	}
}
